package com.simple.util.security;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * @program: simple_tools
 * @description: HMacSHA1加解密
 * @author: Mr.chen
 * @create: 2020-05-18 09:00
 **/
public class HMacSHA1Encrypt {

    /**
     *
     * @param pwd
     * @param data
     * @return
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     * @throws InvalidKeyException
     */
    public static byte[] encode(String pwd, String data) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
        Mac mac = Mac.getInstance("HmacSHA1");
        byte[] keyBytes = pwd.getBytes("UTF8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        mac.init(signingKey);
        byte[] utf8 = data.getBytes("UTF8");
        return mac.doFinal(utf8);
    }

    /**
     *
     * @param Passwd
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String encode(String Passwd) throws NoSuchAlgorithmException {
        MessageDigest alg = MessageDigest.getInstance("SHA-1");
        alg.update(Passwd.getBytes());
        byte[] bts = alg.digest();
        String result = "";
        String tmp = "";
        for (byte bt : bts) {
            tmp = (Integer.toHexString(bt & 0xFF));
            if (tmp.length() == 1) {
                result += "0";
            }
            result += tmp;
        }
        return result;
    }
}
